#pragma once
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <stdlib.h>
#include <string>
using std::cout;
using std::cerr;
using std::endl;
using std::string;

const int backlog=5;

typedef void(*Handler)(int);//函数指针类型

class TcpServer
{
private:
    uint16_t _port;//绑定的port
    int listen_sock;//监听套接字
public:
    TcpServer(uint16_t port)
        :_port(port),listen_sock(-1)
    {}
    void InitTcpServer()
    {
        //1.创建listen_socket套接字文件
        listen_sock=socket(AF_INET,SOCK_STREAM,0);//ipv4协议，socket类型，传输协议编号
        if(listen_sock < 0)
        {
            cerr<<"listen_sock"<<endl;
            exit(1);
        }
        //2.绑定port号及ip地址
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(_port);
        local.sin_addr.s_addr=INADDR_ANY;
        
        if(bind(listen_sock,(struct sockaddr*)&local,sizeof(local)) < 0)
        {
            cerr<<"bind"<<endl;
            exit(2);
        }

        //3.建立监听-允许client进行链接server
        if(listen(listen_sock,backlog)<0)
        {
            cerr<<"listen"<<endl;
            exit(3);
        }
    }
    void Loop(Handler handler)
    {
        //4.执行逻辑-接收链接并进行处理服务
        while(true)
        {
            //和client建立连接关系
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            bzero(&peer,len);
            int sock=accept(listen_sock,(struct sockaddr*)&peer,&len);//真正进行服务的网络文件
            if(sock<0)
            {
                cout<<"accept error"<<endl;
                continue;
            }
            //验证-输出链接client端信息
            uint16_t port=ntohs(peer.sin_port);//网络转主机序列
            string ip=inet_ntoa(peer.sin_addr);//4字节ip转点分十进制ip
            
            cout<<"debug: sock#"<<sock<<" peer_ip#"<<ip<<" peer_port#"<<port<<endl;

            //执行处理逻辑
            handler(sock);

            //close(sock);//处理完关闭网络文件
        }
    }
    ~TcpServer()
    {
        if(listen_sock > 0)
        close(listen_sock);
    }
};

